﻿using System;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Text;
using Texfina.Core.Common;
using Texfina.Common.Mg;
using Texfina.Core.Web;
using Texfina.Core.Data;
using Texfina.Entity.Rh;
using Texfina.Entity.Mg;
using Texfina.Entity.Sy;
using RHBOQry = Texfina.BOQry.Rh;
using MGBOQry = Texfina.BOQry.Mg;
using RHBOMnt = Texfina.BOMnt.Rh;
using SYBOQry = Texfina.BOQry.Sy;

namespace RH
{
   public partial class wfPerPlanillaMnt : EditPage 
   {
      /// <summary>
      /// Guarda el estado de un DataTable, enlazada al control grdListPlani
      /// </summary>
      /// <value></value>
      /// <returns></returns>
      public DataTable DataSourcePlani
      {
         get { return (DataTable)this.ViewState["_dsPlani"]; }
         set { this.ViewState["_dsPlani"] = value; }
      }

      public const int _GRDLIST_STANULADO = 3;

      protected void Page_Load(object sender, EventArgs e)
      {
           if (this.IsPostBack){
               this.LoadInPostBack();
               return;}
           this.LoadData();
      }

      public override void LoadInPostBack()
      {
         this.RegisterGeneralScripts();
      }

      public override void LoadInitialSettings()
      {
         this.FormEditAction = (FormEditAction) Enum.Parse(typeof(FormEditAction), Request.QueryString["formEA"]);
         Label lbl = (Label)this.Master.FindControl("lblTitle");
         lbl.Text = "Asignacion de Planilla";
      }

      public override void LoadListControls()
      { 
         ETablaGenDet objEDet = new ETablaGenDet();
         ETablaPEDet objEDetPE = new ETablaPEDet();
         ECCosto objECCosto = new ECCosto();
         EEmpEstable objEEmp = new EEmpEstable();
         EBanco objEBanco = new EBanco();
         EModContra objEModaC = new EModContra(); 

         IBOQuery objBOCCosto = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(MGBOQry.CCosto));
         IBOQuery objBOBanco = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(MGBOQry.Banco));
         MGBOQry.ITablaGen objBOI = (MGBOQry.ITablaGen)WCFHelper.GetObject<MGBOQry.ITablaGen>(typeof(MGBOQry.TablaGen));
         RHBOQry.ITablaPE objBOIPE = (RHBOQry.ITablaPE)WCFHelper.GetObject<RHBOQry.ITablaPE>(typeof(RHBOQry.TablaPE));
         SYBOQry.IEmpresa objBOEmp = (SYBOQry.IEmpresa)WCFHelper.GetObject<SYBOQry.IEmpresa>(typeof(SYBOQry.Empresa));

         objEDet.IdTabla = ConstMultitabla.TIPO_DOCUMENTO;
         DataTable dt = objBOI.GetDetailByList(objEDet);
         WebHelper.LoadListControl(ddlidTDocIden, dt, "dsAbrev", "idCodigo", true, true);

         objEDet.IdTabla = ConstMultitabla.SEXO;
         dt = objBOI.GetDetailByList(objEDet);
         WebHelper.LoadListControl(ddlidSexo, dt, "dsDescrip", "idCodigo", true, true);
         
      }

      public override void DataToControls()
      {
         EPersonal objE = new EPersonal();
         IBOQuery objBO = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(RHBOQry.Personal));
         objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString() ;
         objE.IdPersonal = Request.QueryString["IdPersonal"];
         objE = (EPersonal)objBO.GetByKey(objE);

         if (objE != null)
         {

            WebHelper.EntityToControl(objE, "IdPersonal", txtidPersonal);
            WebHelper.EntityToControl(objE,"FeNacimien",txtfeNacimiento);
            WebHelper.EntityToControl(objE, "IdSexo", ddlidSexo);

            ECliProv objECli = new ECliProv();
            IBOQuery objBOCli = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(MGBOQry.CliProv));
            objECli.IdCliProv = objE.IdCliProv;
            objECli = (ECliProv)objBOCli.GetByKey(objECli);

            if (objECli != null)
            {
               WebHelper.EntityToControl(objECli,"IdCliProv",hdnidCliProv);
               WebHelper.EntityToControl(objECli,"DsAPaterno",txtdsAPaterno);
               WebHelper.EntityToControl(objECli,"DsAMaterno",txtdsAMaterno);
               WebHelper.EntityToControl(objECli,"DsNombres",txtdsNombres);
               WebHelper.EntityToControl(objECli,"IdTDocIden",ddlidTDocIden);
               WebHelper.EntityToControl(objECli, "NuDocIden", txtnuDocIden);
               WebHelper.EntityToControl(objECli,"NuTelf",txtnuTelf);
               WebHelper.EntityToControl(objECli,"NuFax",txtnufax);
               WebHelper.EntityToControl(objECli,"DsEmail",txtdsEmail);
               WebHelper.EntityToControl(objECli,"DsWeb", txtdsWeb);
            }
         }

         EPersonal objEDet = new EPersonal();
         RHBOQry.IPersonal objBODet = (RHBOQry.IPersonal)WCFHelper.GetObject<RHBOQry.IPersonal>(typeof(RHBOQry.Personal));
         objEDet.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
         objEDet.IdPersonal = Request.QueryString["IdPersonal"];
         DataTable dt = objBODet.GetPlanillaXPersonal(objEDet);

         this.GridSetDataBinding(grdList, dt);

      }

      public override void RegisterGeneralScripts()
      { 
         txtidPersonal.Attributes.Add("readonly", "true");

         StringBuilder sb = new StringBuilder();

         sb.AppendLine("function validateEditForm(key){");
         sb.AppendLine("var varRpta = isEmptyControl('" + txtdsAPaterno.ClientID + "','Ingrese el Apellido Paterno');");
         sb.AppendLine("if(varRpta==true){");
         sb.AppendLine("document.getElementById('" + txtdsAPaterno.ClientID + "').focus();return !varRpta;}");
         sb.AppendLine("var varRpta = isEmptyControl('" + txtdsAMaterno.ClientID + "','Ingrese el Apellido Materno');");
         sb.AppendLine("if(varRpta==true){");
         sb.AppendLine("document.getElementById('" + txtdsAMaterno.ClientID + "').focus();return !varRpta;}");
         sb.AppendLine("var varRpta = isEmptyControl('" + txtdsNombres.ClientID + "','Ingrese los Nombres');");
         sb.AppendLine("if(varRpta==true){");
         sb.AppendLine("document.getElementById('" + txtdsNombres.ClientID + "').focus();return !varRpta;}");
         sb.AppendLine("var varRpta = isEmptyControl('" + ddlidTDocIden.ClientID + "','Seleccione el tipo de Documento de Identidad');");
         sb.AppendLine("if(varRpta==true){");
         sb.AppendLine("document.getElementById('" + ddlidTDocIden.ClientID + "').focus();return !varRpta;}");
         sb.AppendLine("var varRpta = isEmptyControl('" + txtnuDocIden.ClientID + "','Ingrese el numero de Documento de Identidad');");
         sb.AppendLine("if(varRpta==true){");
         sb.AppendLine("document.getElementById('" + txtnuDocIden.ClientID + "').focus();return !varRpta;}");
         sb.AppendLine("var varRpta = isEmptyControl('" + txtfeNacimiento.ClientID + "','Seleccione o ingrese la fecha de Nacimiento');");
         sb.AppendLine("if(varRpta==true){");
         sb.AppendLine("document.getElementById('" + txtfeNacimiento.ClientID + "').focus();return !varRpta;}");
         sb.AppendLine("var varRpta = isEmptyControl('" + ddlidSexo.ClientID + "','Seleccione el Genero');");
         sb.AppendLine("if(varRpta==true){");
         sb.AppendLine("document.getElementById('" + ddlidSexo.ClientID + "').focus();return !varRpta;}");
         sb.AppendLine("var varRpta = isEmptyControl('" + txtnuTelf.ClientID + "','Ingrese el numero de telefono');");
         sb.AppendLine("if(varRpta==true){");
         sb.AppendLine("document.getElementById('" + txtnuTelf.ClientID + "').focus();return !varRpta;}");
         sb.AppendLine("menu_doPostBack('"+mnuToolbar.ClientID+"','"+mnuToolbar.UniqueID+"',key);");
         sb.AppendLine("}");

         //sb.AppendLine("function validateEditFormGrid(key){");
         //sb.AppendLine("varRpta = gridFindCellValueInRow('" + grdList.ClientID + "',new Array(" + _GRDLIST_STCONTRATO + "," + _GRDLIST_STANULADO + "), new Array(" + ConstFlagEstado.DESACTIVADO + "," + ConstFlagEstado.DESACTIVADO + "),'Solo puede existir un contrato Activo, deshabilite los actuales.');");
         //sb.AppendLine("if(varRpta==true)");
         //sb.AppendLine("return !varRpta;");
         //sb.AppendLine("menu_doPostBack('" + mnuGrid.ClientID + "','" + mnuGrid.UniqueID + "',key);");
         //sb.AppendLine("}");

         ScriptManager.RegisterStartupScript(this, this.GetType(), "ScriptRegister", sb.ToString(), true);
      }

      public void RegisterEditPopupScripts()
      {
         StringBuilder sb = new StringBuilder();

         sb.AppendLine("function validate" + this.bttOkPopup.ID + "(){");
         //sb.AppendLine("varRpta = isEmptyControl('" + this.txtfeSuscripcion.ClientID + "','Ingrese el fecha de Suscripcion.');");
         //sb.AppendLine("if(varRpta==true)");
         //sb.AppendLine("return !varRpta;");
         //sb.AppendLine("varRpta = isEmptyControl('" + this.txtfeInicio.ClientID + "','Ingrese la fecha de Inicio.');");
         //sb.AppendLine("if(varRpta==true)");
         //sb.AppendLine("return !varRpta;");
         //sb.AppendLine("varRpta = isEmptyControl('" + this.txtfeFin.ClientID + "','Ingrese la fecha Fin.');");
         //sb.AppendLine("if(varRpta==true)");
         //sb.AppendLine("return !varRpta;");
         //if (this.GridEditAction == GridEditAction.Delete)
         //{
         //   sb.AppendLine("varRpta = isEmptyControl('" + this.ddlidMotivFin.ClientID + "','Selecciona el motivo de Cese.');");
         //   sb.AppendLine("if(varRpta==true)");
         //   sb.AppendLine("return !varRpta;");
         //}

         //sb.AppendLine("varRpta = isEmptyControl('" + this.ddlidPuesto.ClientID + "','Seleccione el Puesto.');");
         //sb.AppendLine("if(varRpta==true)");
         //sb.AppendLine("return !varRpta;");
         //sb.AppendLine("varRpta = isEmptyControl('" + this.ddlidFuncion.ClientID + "','Seleccione la Funcion.');");
         //sb.AppendLine("if(varRpta==true)");
         //sb.AppendLine("return !varRpta;");
         //sb.AppendLine("varRpta = isEmptyControl('" + this.ddlidModalidad.ClientID + "','Seleccione la Modalidad.');");
         //sb.AppendLine("if(varRpta==true)");
         //sb.AppendLine("return !varRpta;");
         //sb.AppendLine("varRpta = isEmptyControl('" + this.ddlidSubModal.ClientID + "','Seleccione la SubModalidad.');");
         //sb.AppendLine("if(varRpta==true)");
         //sb.AppendLine("return !varRpta;");
         //sb.AppendLine("varRpta = isEmptyControl('" + this.ddlidGrpOcupac.ClientID + "','Seleccione el Grupo de Ocupacion.');");
         //sb.AppendLine("if(varRpta==true)");
         //sb.AppendLine("return !varRpta;");
         //sb.AppendLine("varRpta = isEmptyControl('" + this.ddlidRemVariable.ClientID + "','Seleccione el tipo de Remuneracion.');");
         //sb.AppendLine("if(varRpta==true)");
         //sb.AppendLine("return !varRpta;");
         //sb.AppendLine("varRpta = isEmptyControl('" + this.ddlidMoneda.ClientID + "','Seleccione el tipo de Moneda.');");
         //sb.AppendLine("if(varRpta==true)");
         //sb.AppendLine("return !varRpta;");
         //sb.AppendLine("varRpta = isEmptyControl('" + this.txtmtRemunera.ClientID + "','Ingrese el monto de remuneracion.');");
         //sb.AppendLine("if(varRpta==true)");
         //sb.AppendLine("return !varRpta;");
         sb.AppendLine("return true;}");

         ScriptManager.RegisterStartupScript(this, this.GetType(), "validatePopup", sb.ToString(), true);

         this.bttOkPopup.OnClientClick = "return validate" + bttOkPopup.ID + "();";
         this.bttCancelPopup.OnClientClick = "$find('" + this.mdlPopup.ClientID + "').hide();return false;";
       
      }

      protected void mnuToolbar_MenuItemClick(Object sender, MenuEventArgs e)
      {
         if(e.Item == null)
            return;

         switch (e.Item.Value)
         {
            case ConstMenuToolbarValue.BUTTON_SAVE:
            case ConstMenuToolbarValue.BUTTON_SAVENEW:
               if(this.FormEditAction != FormEditAction.Delete)
                  this.SaveData(e.Item.Value);
               else
                  this.DeleteData();
               break; 

            case ConstMenuToolbarValue.BUTTON_EXIT:
               this.Response.Redirect("wfPerPlanillaBnd.aspx?Filter=1");
               break;
      
         }
        
      }

      protected void mnuGrid_MenuItemClick(Object sender, MenuEventArgs e)
      {
         if (e.Item == null)
            return;

         switch (e.Item.Value)
         {
            case ConstMenuToolbarValue.BUTTON_NEW:
               this.GridEditAction = GridEditAction.AddNew;
               this.lblTitlePopup.Text = "Planilla (Seleccione)";
               this.mdlPopup.Show();
               this.LoadDataEditPopup(grdList, -1);
               this.RegisterEditPopupScripts();
               break;
         }

      }

      protected void grdList_RowCommand(Object sender, GridViewCommandEventArgs e)
      {
         this.EditRowIndex = Convert.ToInt32(e.CommandArgument);

         switch (e.CommandName)
         {
            case ConstGridRowCommand.GRIDDELETE:
               this.GridEditAction = GridEditAction.Delete;
               DataRow dr = this.GridGetRowFromDataKey(this.DataSource, grdList, this.EditRowIndex);
               //dr.BeginEdit();
               dr["stAnulado"] = ConstFlagEstado.ACTIVADO;
               //dr.EndEdit(); 
               grdList.DataSource = this.DataSource;
               grdList.DataBind();

               break;
         }
      }

      protected void grdList_RowDataBound(Object sender, GridViewRowEventArgs e)
      {
         if (e.Row.RowType == DataControlRowType.DataRow)
         {
            String strRI = e.Row.RowIndex.ToString();

            ImageButton bttdelete = (ImageButton)e.Row.FindControl("grdBtt" + ConstGridRowCommand.GRIDDELETE);

            bttdelete.OnClientClick = "javascript:return validateGridCommands('" + ConstGridRowCommand.GRIDDELETE + "','" + strRI + "');";

            if (e.Row.Cells[_GRDLIST_STANULADO].Text == ConstFlagEstado.ACTIVADO)
            { 
               e.Row.ForeColor = System.Drawing.Color.Red;
               bttdelete.ImageUrl = "../Images/Icons/Disabled/Delete.png";
            }
         }

      }

      protected void grdListPlani_RowDataBound(Object sender, GridViewRowEventArgs e)
      {
         if (e.Row.RowType == DataControlRowType.Header)
         {
            CheckBox chkAllChecked = new CheckBox();
            chkAllChecked.ID = "chkAllCheck";
            chkAllChecked.Checked = false;
            chkAllChecked.Attributes.Add("onClick", "SelectedCheckBoxAll(this);");
            e.Row.Cells[0].Controls.Add(chkAllChecked);
         }

      }


      protected void bttOkPopup_Click(object sender, EventArgs e)
      {
         foreach (GridViewRow grdRow in grdListPlani.Rows)
         {
            CheckBox ctlChk = (CheckBox)grdRow.FindControl("chkSelected");
            if(!ctlChk.Checked)
               continue;

            DataRow dr = this.GridGetRowFromDataKey(this.DataSourcePlani, grdListPlani, Convert.ToInt32(grdRow.RowIndex));

            DataRow[] drEva = this.DataSource.Select("idPlanilla = " + dr["idPlanilla"]);

            if (drEva.Length != 0)
               drEva[0]["stAnulado"] = ConstFlagEstado.DESACTIVADO;
            else
            {
               DataRow drNew = this.DataSource.NewRow();
               drNew["idEmpresa"] = Session[ConstSessionVar.EMPRESA].ToString();
               drNew["idPersonal"] = this.txtidPersonal.Text;
               drNew["idPlanilla"] = dr["idPlanilla"];
               drNew["dsPlanilla"] = dr["dsPlanilla"];
               drNew["stAnulado"] = ConstFlagEstado.DESACTIVADO;
               this.DataSource.Rows.Add(drNew);
            }
            grdList.DataSource = this.DataSource;
            grdList.DataBind();
         }
         
      }

      public override void LoadDataEditPopup(GridView grid, int rowIndex)
      {
         EPlanilla objE = new EPlanilla();
         objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
         IBOQuery objBO = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(RHBOQry.Planilla));
         DataTable dt = objBO.GetList(objE);
         
         foreach (DataRow dr in this.DataSource.Rows)
         {
            DataRow[] drdel = dt.Select("idPlanilla=" + dr["idPlanilla"] + " and stAnulado=" + dr["stAnulado"]);
            if (drdel.Length != 0) 
            dt.Rows.Remove(drdel[0]); 
         }

         this.DataSourcePlani = dt;
         this.grdListPlani.DataSource = dt;
         this.grdListPlani.DataBind();
         
      }
      
      public new void ClearEditPopup()
      {
         //this.txtfeSuscripcion.Text = "";
         //this.txtfeInicio.Text = "";
         //this.txtfeFin.Text = "";
         //this.ddlidMotivFin.SelectedIndex = 0;
         ////this.ddlidPuesto.SelectedIndex = 0;
         ////this.ddlidFuncion.SelectedIndex = 0;
         //this.ddlidModalidad.SelectedIndex = 0;
         //this.ddlidSubModal.SelectedIndex = 0;
         //this.ddlidGrpOcupac.SelectedIndex = 0;
         //this.ddlidRemVariable.SelectedIndex = 0;
         //this.ddlidMoneda.SelectedIndex = 0;
         //this.txtmtRemunera.Value = 0;
         //this.rdDiscaNo.Checked = true;
         //this.rdRemEspeNo.Checked = true; 
      }

      public void LockControlsPopup()
      {
         //if (this.GridEditAction == GridEditAction.Delete || _STCONTRATO == ConstFlagEstado.ACTIVADO )
         //{
         //   if (_STCONTRATO == ConstFlagEstado.ACTIVADO)
         //      this.ddlidMotivFin.Enabled = true;
         //   else
         //      this.ddlidMotivFin.Enabled = false;
         //      this.txtfeSuscripcion.Enabled = false;
         //      this.txtfeInicio.Enabled = false;
         //      this.txtfeFin.Enabled = false;
         //      //this.ddlidPuesto.Enabled = false;
         //      //this.ddlidFuncion.Enabled = false;
         //      this.ddlidModalidad.Enabled = false;
         //      this.ddlidSubModal.Enabled = false;
         //      this.ddlidGrpOcupac.Enabled = false;
         //      this.ddlidRemVariable.Enabled = false;
         //      this.ddlidMoneda.Enabled = false;
         //      this.txtmtRemunera.Enabled = false;
         //      this.rdDiscaNo.Enabled = false;
         //      this.rdDiscaSi.Enabled = false;
         //      this.rdRemEspeNo.Enabled = false;
         //      this.rdRemEspeSi.Enabled = false;
         //}
         //else
         //      this.ddlidMotivFin.Enabled = false;
      }

      public override void SaveData(String key)
      {
           if (this.ValidateData() == false )
            return;

            IEntityBase objE= (IEntityBase) this.CreateEntitySet();
            IBOUpdate objPro = (IBOUpdate)WCFHelper.GetObject<IBOUpdate>(typeof(RHBOMnt.Personal));

            String[] strRet = objPro.UpdateData(objE);
            String strMsg = "";

            switch (this.FormEditAction)
            { 
            
               case FormEditAction.AddNew:
               case FormEditAction.Copy:
                     strMsg = "Se ha registrado los Contratos : " + strRet[0].ToString() ;
                     break;
               default:
                     strMsg = "Se ha modificado los Contratos : " + txtidPersonal.Text;
                     break;
            }
            this.hdnMsgOPB.Value = this.CreatePostbackMessage("CORRECTO", strMsg, TypeMessageAlert.correct, false, "wfPerPlanillaBnd.aspx?Filter=1");
      }

      public override void DeleteData()
      {
            IEntityBase objE= (IEntityBase)this.CreateEntitySet();
            IBOUpdate objPro = (IBOUpdate)WCFHelper.GetObject<IBOUpdate>(typeof(RHBOMnt.Personal));
            objPro.DeleteData(objE);

            this.hdnMsgOPB.Value = this.CreatePostbackMessage("CORRECTO", "Se anulo el derechohabiente  : " + txtidPersonal.Text, TypeMessageAlert.correct, false, "wfPerDereHabiBnd.aspx?Filter=1");
       
      }

      public override Object CreateEntitySet()
      {

            DataTable dt= (DataTable)this.DataSource;
            this.ClearDeletedRow(this.DataSource, "stAnulado");
            IList<EPerPlanilla> colEContra = new List<EPerPlanilla>();

            if( this.FormEditAction == FormEditAction.Delete )
            {
                  foreach(DataRow dr in dt.Rows)
                  {
                     this.MarkDeletedRow(dr, "stAnulado");
                  }
            }
       
            for (int intTypeUpd = 0; intTypeUpd<=1; intTypeUpd++)
            {
               DataTable dtChange= null;
               if( intTypeUpd == 0 )
                  dtChange = dt.GetChanges(DataRowState.Added);
               else
                  dtChange = dt.GetChanges(DataRowState.Modified);
         
               if (dtChange != null )
               {
                  foreach(DataRow drDet in dtChange.Rows)
                  {
                     EPerPlanilla objEDet = DataHelper.CopyDataRowToEntity<EPerPlanilla>(drDet, typeof(EPerPlanilla));

                     if(drDet.RowState == DataRowState.Added)
                        objEDet.EntityState = EntityState.Added;
               
                     if(drDet.RowState == DataRowState.Modified)
                     {
                        if(objEDet.StAnulado == ConstFlagEstado.DESACTIVADO)
                           objEDet.EntityState = EntityState.Modified;
                        else
                           objEDet.EntityState = EntityState.Deleted;
                     }

                     colEContra.Add(objEDet);
                  }
               }
            }
         
            EPersonalSet objESet = new EPersonalSet();
            objESet.ColPerPlanilla = colEContra; 

          return objESet;
      }
    
      public override void LockControls()
      {
  
      }

   }
}